﻿using DotNetCore.CAP;
using DotNetCore.CAP.Transport;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharedKernel.Infrastructure.Extes
{
    public static class ISqlSugarClientExtensions
    {
        public static ICapTransaction BeginCapTransaction(this ISqlSugarClient sugarClient, ICapPublisher publisher, bool autoCommit = false)
        {
            var dispatcher = publisher.ServiceProvider.GetRequiredService<IDispatcher>();
            sugarClient.Ado.BeginTran();
            var transaction = new SqlSugarTransaction(dispatcher, sugarClient.Ado)
            {
                AutoCommit = autoCommit
            };
            return publisher.Transaction = transaction;
        }
    }

    public class SqlSugarTransaction : CapTransactionBase
    {
        public SqlSugarTransaction(IDispatcher dispatcher, IAdo ado) : base(dispatcher)
        {
            Ado = ado;
            DbTransaction = ado.Transaction;
        }

        public IAdo Ado { get; set; }

        public override void Commit()
        {
            Ado.CommitTran();
            Flush();
        }

        public override async Task CommitAsync(CancellationToken cancellationToken = default)
        {
            await Ado.CommitTranAsync();
            Flush();
        }

        public override void Dispose()
        {
            Ado.Dispose();
        }

        public override void Rollback()
        {
            Ado.RollbackTran();
        }

        public override async Task RollbackAsync(CancellationToken cancellationToken = default)
        {
            await Ado.RollbackTranAsync();
        }
    }


}
